'use strict';

const path = require('path');
const fs = require('fs');

const Controller = require('egg').Controller;

class GetLogsController extends Controller {
    async logsList() {

        const {
            app,
            ctx
        } = this;

        try {

            const logsPath = path.join(app.baseDir, `/logs/${app.name}`);
            const fileList = fs.readdirSync(logsPath);

            let logsData = [];

            for (let i in fileList) {
                logsData[i] = {
                    name: fileList[i],
                    link: ctx.protocol + '://' + ctx.host + '/logs/' + fileList[i]
                }
            };

            await ctx.render('logsList.ejs', {
                logsData
            });

        } catch (error) {
            ctx.logger.error(error);
        }

    }

    async logsContent() {
        const {
            app,
            ctx
        } = this;

        try {
            const logsName = ctx.params.name;
            const logsPath = path.join(app.baseDir, `/logs/${app.name}/${logsName}`);
            const isExist = fs.existsSync(logsPath);

            if (isExist) {
                const logsData = fs.readFileSync(logsPath);
                ctx.body = logsData.toString();
            }
        } catch (error) {
            ctx.logger.error(error);
        }

    }
}

module.exports = GetLogsController;